<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use app\Common;
use app\model\UserModel;

//控制器
class Trash{
    //常用数据表内容 及常用字典
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";         

    public function __construct(){
        // $gm=new GoodsModel();
        // $this->goods = $gm->getAll();
        // $cm=new CatModel();
        // $this->cats = $cm->catTree();
        $um=new UserModel();
        $this->users = $um->getAll();

    }
    public function __call($method,$args){
        return '<div style="margin:0 auto;color:red;text-align:center;"><h1>此功能尚未开放!</h1></div>'.$this->back;
    }

    //类别
    public function index(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $list=Db::table('trash')->paginate(15)->toArray();

        foreach($list as &$kv){

        }
        //halt($list);

        View::assign(['list'=>$list]);

        return View::fetch();
    }  

    //恢复数据
    public function restore($table,$id){
        $all=Request::param();

        if(empty($table)) $table=$all['table'];
        if(empty($id)) $table=$all['id'];

        $row=Db::table('trash')->find($id);
        if(!$row) {
            return json(['code'=>0,'msg'=>'Error']);
        }

        $data=json_decode($row['data'],true);
        $old_id=$data['id'];

        //这里直接删除
        if(!empty($all['erase'])){
            $res =Db::table('trash')->delete($id);
            Db::execute('OPTIMIZE TABLE trash');
            if($row['table_name']=='order'){
                Db::execute('delete from order_list where order_id=?',[$old_id]);
                Db::execute('delete from order_log where order_id=?',[$old_id]);
                Db::execute('OPTIMIZE TABLE order_list');
                Db::execute('OPTIMIZE TABLE order_log');
            }
            return header('location:/trash/index');
        }

        unset($data['id']);
        $new_id = Db::table($table)->insertGetid($data);

        //恢复订单数据
        if($new_id && $row['table_name']=='order'){
            Db::execute('update order_list set order_id=? where order_id=?',[$new_id,$old_id]);
            Db::execute('update order_log set order_id=? where order_id=?',[$new_id,$old_id]);
        }

        $res = Db::table('trash')->delete($id);
        Db::execute('OPTIMIZE TABLE trash');

        return header('location:/trash/index');
    }


    


}
